package com.sz.app.oss.api.common.base;

import com.sz.app.oss.constants.MessagesCodes;
import com.sz.app.oss.constants.Permissions;
import com.sz.biz.app.web.BaseController;
import com.sz.biz.common.base.entity.SettlementType;
import com.sz.biz.common.base.service.SettlementTypeService;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dto.I18nDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.service.I18nBaseService;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.app.oss.api.common.base.dto.SettlementTypeDto;
import io.swagger.annotations.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Function: 结算方式 controller <br>
 * Author: hpeng.wang <br>
 * Date: 2016-11-25 11:08:00
 */

@RestController
@RequestMapping("${api}/biz/settypes")
@Api(description = " ", tags = "023、结算方式管理")
public class SettlementTypeController extends BaseController {
    @Autowired
    private SettlementTypeService service;
    @Autowired
    private I18nBaseService i18nService;
    @Value("${i18n.biz.settlement.type}")
    private String i18nTable;


    /**
     * 新增结算方式
     *
     * @param dto 要保存的对象
     * @return 操作的结果
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @ApiOperation(value = "新增", notes = "新增结算方式数据<br>权限：" + Permissions.BIZ_MGT_BASE_SETTYPE)
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_SETTYPE)
    public ResultDto save(@ApiParam(required = true) @RequestBody SettlementTypeDto dto) throws Exception {
        SettlementType entry = new SettlementType();
        dto.setId(null);
        EntityUtils.copyPropertiesIgnoreNull(dto, entry);
        entry.setLastUpdateTime(new Date());

        int id = service.save(entry);
        i18nService.save(id, dto.getI18n(), i18nTable);
        ResultDto result = getSaveSuccessDto(MessagesCodes.MODULE_SETTYPE);
        result.setData(id);
        return result;
    }


    /**
     * 删除结算方式
     *
     * @param ids 要删除数据的集合
     * @return 操作的结果信息
     */
    @ApiOperation(value = "删除", notes = "根据指定id删除结算方式<br>权限：" + Permissions.BIZ_MGT_BASE_SETTYPE, httpMethod = "POST")
    @RequestMapping(value = "/deletions", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_SETTYPE)
    public ResultDto batchDelete(@RequestBody @ApiParam(value = "要删除的id集合", required = true) List<Integer> ids)
            throws Exception {
        service.batchdelete(ids);

        List<SettlementType> list = service.findByIds(ids);
        //数据备份
        Map<String, Object> dataBackup = new HashedMap();
        dataBackup.put(UserActions.DELETE, list);
        ResultDto dto = getDeleteSuccessDto(MessagesCodes.MODULE_SETTYPE);
        return dto;
    }


    /**
     * 修改结算方式.
     */
    @RequestMapping(value = "{id}", method = {RequestMethod.POST})
    @ApiOperation(value = "修改结算方式", notes = "修改结算方式数据<br>权限：" + Permissions.BIZ_MGT_BASE_SETTYPE)
    @Transactional(propagation = Propagation.REQUIRED)
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_SETTYPE)
    public ResultDto update(@PathVariable int id, @RequestBody SettlementTypeDto dto) throws Exception {
        SettlementType entry = service.findById(id);
        int count = 0;
        if (entry != null) {
            dto.setId(null);
            EntityUtils.copyPropertiesIgnoreNull(dto, entry);
            entry.setLastUpdateTime(new Date());
            count = service.update(entry);
            i18nService.save(id, dto.getI18n(), i18nTable);
        }
        ResultDto result = getUpdateSuccessDto(MessagesCodes.MODULE_SETTYPE);
        result.setData(count);
        return result;
    }

    /**
     * 根据id查询结算方式
     *
     * @param id 结算方式的id
     * @return 查询到的单条结算方式
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "根据id获取结算方式", notes = "根据id获取到的结算方式")
    public ResultDto findById(@ApiParam(value = "结算方式id", required = true) @PathVariable Integer id)
            throws Exception {
        SettlementTypeDto dto = new SettlementTypeDto();
        SettlementType entry = service.findById(id);
        if (entry != null) {
            EntityUtils.copyPropertiesIgnoreNull(entry, dto);
            List<I18nDto> list = i18nService.findI18nDtoByRefId(i18nTable, entry.getId());
            dto.setI18n(list);
        }
        ResultDto result = new ResultDto();
        result.setData(dto);
        return result;


    }


    /**
     * 根据条件获取数据集合
     *
     * @param q         参数信息
     * @param pageIndex 哪页
     * @param pageSize  分页大小
     * @param sort      排序字段的名称
     * @param asc       true asc false desc
     * @return 查询的数据集合
     */
    @ApiOperation(value = "查询", notes = "根据指定条件获取数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue
                    = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true")
    })

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResultDto findByParam(@RequestParam(required = false) String q,
                                 @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                 @RequestParam(required = false, defaultValue = "10") int pageSize,
                                 @RequestParam(required = false) String sort,
                                 @RequestParam(required = false, defaultValue = "true") Boolean asc) throws Exception {
        q = StringUtils.replaceSqlPattern(q);
        ResultDto resultDto = service.findByParam(new QueryParams(pageSize, pageIndex, q, sort, asc));
        return resultDto;
    }

    /**
     * 批量新增或修改国际化.
     *
     * @param dtos 要保存或修改的国际化实体集合
     * @return 处理成功与否的返回信息
     */
    @ApiOperation(value = "新增或修改i18n", notes = "批量新增或修改结算方式国际化<br>权限：" + Permissions.BIZ_MGT_BASE_SETTYPE)
    @RequestMapping(value = "i18n", method = {RequestMethod.POST})
    @RequiresPermissions(Permissions.BIZ_MGT_BASE_SETTYPE)
    public ResultDto saveI18n(@RequestBody @ApiParam(value = "要处理的实体", required = true) List<I18nDto> dtos) throws
            Exception {
        i18nService.save(dtos, i18nTable);
        service.refreshCache();
        ResultDto result = this.getSaveI18nSuccessDto();
        return result;
    }

    /**
     * 根据条件获取国际化数据集合
     *
     * @param language  语言信息
     * @param q         参数信息
     * @param pageIndex 哪页
     * @param pageSize  分页大小
     * @param unfilled  是否未添加国际化字段，true，代表未添加，fasle与null代表所有
     * @param sort      排序字段的名称
     * @param asc       true asc false desc
     * @return 查询的国际化数据集合
     */
    @ApiOperation(value = "查询i18n", notes = "根据指定条件获取国际化数据集合")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言信息", dataType = "string", paramType = "path", required =
                    true),
            @ApiImplicitParam(name = "q", value = "模糊查询参数", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页", dataType = "int", paramType = "query", defaultValue =
                    "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数,max<2000", dataType = "int", paramType = "query",
                    defaultValue = "10"),
            @ApiImplicitParam(name = "unfilled", value = "是否未添加国际化字段，true，代表未添加，fasle与null代表所有", dataType = "boolean", paramType = "query", defaultValue =
                    "false"),
            @ApiImplicitParam(name = "sort", value = "排序的字段", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue =
                    "true")
    }

    )
    @RequestMapping(value = "i18n/{language}", method = RequestMethod.GET)
    public ResultDto findI18n(@PathVariable String language,
                              @RequestParam(required = false) String q,
                              @RequestParam(required = false, defaultValue = "1") int pageIndex,
                              @RequestParam(required = false, defaultValue = "10") int pageSize,
                              @RequestParam(required = false, defaultValue = "false") Boolean unfilled,
                              @RequestParam(required = false) String sort,
                              @RequestParam(required = false, defaultValue = "true") Boolean asc) throws Exception {
        q = StringUtils.replaceSqlPattern(q);
        ResultDto resultDto = service.findI18nByParam(new QueryParams(pageSize, pageIndex, q, sort, asc, language).put("unfilled", unfilled));
        return resultDto;
    }

    /**
     * 异步校验结算方式的code
     *
     * @param code 结算方式code
     * @param sid  　结算方式id，修改时传id，新增时为NULL
     * @return　校验的结果
     */
    @ApiOperation(value = "异步校验结算方式名编码", notes = "异步校验结算方式编码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "结算方式编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sid", value = "结算方式id 修改时传id 新增时传空", dataType = "int", paramType = "query")})
    @RequestMapping(value = "/feetypecheckcode", method = {RequestMethod.GET})
    public ResultDto checkCode(@RequestParam String code,
                               @RequestParam(required = false, defaultValue = "0") int sid) {
        service.checkCode(sid, code);
        return new ResultDto();
    }
}
